package fr.webviewer.transformation;

import java.util.Set;

import android.graphics.Point;
import android.graphics.Rect;
import fr.webviewer.data.RoadEntry;

public class ScreenMapping {

	public static Point getScroll(Rect imageAreaToShow, WebViewZoom zoom) {
		Point result = new Point();
		if (!imageAreaToShow.isEmpty()) {
			result.set(Float.valueOf(imageAreaToShow.left * zoom.getZoom()).intValue(), Float.valueOf(imageAreaToShow.top * zoom.getZoom()).intValue());
		}
		return result;
	}

	public static WebViewZoom getZoom(Rect screen, Rect image, Rect imageAreaToShow, float actualZoom) {
		WebViewZoom result = new WebViewZoom();
		result.setZoom(actualZoom);
		float target;
		if (!imageAreaToShow.isEmpty()) {
			imageAreaToShow.intersect(image);
			float zoomWidth = (float)screen.width() / imageAreaToShow.width();
			float zoomHeight = (float)screen.height() / imageAreaToShow.height();
			if (zoomWidth > zoomHeight) {
				target = zoomHeight;
			} else {
				target = zoomWidth;
			}
			if(result.getZoom() * 1.25F < target){
				while(result.getZoom() < target){
					result.setZoom(result.getZoom() * 1.25F);
					result.setZoomStep(result.getZoomStep() + 1);
				}				
			} else {
				while(result.getZoom() / 1.25F > target){
					result.setZoom(result.getZoom() / 1.25F);
					result.setZoomStep(result.getZoomStep() - 1);
				}				
			}
		} 
		return result;
	}

	public static Rect getImageAreaToShow(Set<RoadEntry> entryList) {
		Rect result = new Rect();
		for (RoadEntry entry : entryList) {
			makeRectangleIncludePoint(result, entry.getPosition());
		}
		addMargin(result, 50);
		return result;
	}

	public static void makeRectangleIncludePoint(Rect r, Point p) {
		if (r.left == 0 && r.top == 0 && r.right == 0 && r.bottom == 0) {
			r.left = p.x;
			r.top = p.y;
			r.right = p.x;
			r.bottom = p.y;
		} else {
			r.union(p.x, p.y);
		}
	}

	public static void addMargin(Rect r, int margin) {
		r.left = r.left - margin;
		r.top = r.top - margin;
		r.right = r.right + margin;
		r.bottom = r.bottom + margin;
	}

}
